package com.keffect.effects.animatedEffects;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import com.keffect.effects.AnimatedEffect;

/**
 * 
 * @author Matias Varela
 *         <p>
 *         Student of Licenciatura en Ciencias de la Computacion, at the
 *         Universidad Nacional del Sur (Argentina).
 *         <p>
 *         project site: http://code.google.com/p/keffect-project/
 * 
 */
public class Shadow extends AnimatedEffect {

	// effect variables

	private static final int RULE = AlphaComposite.SRC_ATOP;
	private Composite[] comps;
	private int compsIndex = 0;
	private Composite comp;
	private Color compColor;

	private Rectangle r;
	private boolean isInit;


	// *******************

	public Shadow(long duration) {
		super(duration);
		this.setFrames((long) (60 * Math.ceil((float) duration / 1000)) / 2);
		isInit = false;
		compColor = Color.black;
	}


	public Shadow(long duration, Color color) {
		super(duration);
		this.setFrames((long) (60 * Math.ceil((float) duration / 1000)) / 2);
		isInit = false;

		compColor = color;
	}


	@Override
	public void initEffectProperties() {
		if (!isInit) {
			r = new Rectangle(0, 0, getEffectPanel().getWidth(), getEffectPanel().getHeight());
			comps = new Composite[(int) getFrames()];
			for (int i = 0; i < comps.length; i++) {
				float alpha = (float) Math.cos(Math.PI * i / getFrames());
				alpha += 1;
				alpha /= 2;
				comps[i] = AlphaComposite.getInstance(RULE, alpha);
			}
			isInit = true;
		}
		this.compsIndex = 0;

	}


	@Override
	public boolean isRunning() {
		return (compsIndex < comps.length - 1);
	}


	@Override
	public void run() {
		comp = comps[compsIndex];
		compsIndex++;
	}


	@Override
	public void doPaintBefore(Graphics2D g) {

	}


	@Override
	public void doPaintAfter(Graphics2D g) {
		Color defaultColor = g.getColor();
		g.setColor(compColor);

		g.setComposite(comp);
		g.fill(r);
		g.setComposite(comps[(comps.length - 1) - compsIndex]);

		g.setColor(defaultColor);

	}
}
